<?php
/**
 * Import Controller class file 
 */

/**
 * ImportController 
 * 
 * @uses MyController
 * @package admin
 * @version $Id: ImportController.php 3 2011-08-31 07:46:15Z juppwerner@googlemail.com $
 * @copyright 2010 Adam OPEL GmbH
 * @author Joachim Werner <joachim.pt.werner@de.gm.com> 
 * @license (tbd)
 */
class ImportController extends MyController
{
    // {{{ *** Members ***

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    // public $layout='//layouts/column2';

    public $title='Import';

    // }}} End Members
    // {{{ *** Actions ***
    // {{{ actionIndex
    public function actionIndex()
    {
        $this->checkAccess('admin');
        
        $this->render('index');
    } // }}} 
    // {{{ actionDo
    public function actionDo()
    {
        // {{{ Check access
        switch($_GET['spec'])
        {
            case 'fprlateitems':
                $this->checkAccess('importFPRLateItems');
                break;
            case 'top25IptvCc':
                $this->checkAccess('importTop25IptvCc');
                break;
            case 'vehiclebuybacks':
                $this->checkAccess('importVehicleBuybacks');
                break;
            default:
                $this->checkAccess('admin');
                break;
        }
        // }}} 
        ini_set('max_execution_time',10*60);
        $model                      = new ImportForm;
        $model->initImportSpec($_GET['spec']);
        $importTitle                = $model->importSpec['title'];
        $destModelName              = $model->importSpec['model'];
        $model->csvFieldSeparator   = $model->importSpec['csvFieldSeparator'];
        $model->truncateTable       = $model->importSpec['truncateTable'];        
        $model->disableyKeys        = 0; //$model->importSpec['disableyKeys'];        
        $model->lockTable           = 0; //$model->importSpec['lockTable'];        
        $model->skipFirstNumLines   = $model->importSpec['skipFirstNumLines'];
        $model->loadNbrOfLines      = $model->importSpec['loadNbrOfLines'];
        $model->prepareDateAttributesOnSave
            = isset($model->importSpec['prepareDateAttributesOnSave'])
            ? $model->importSpec['prepareDateAttributesOnSave']
            : 1;
        // {{{ Was form with import parameters submitted?
        if(isset($_POST['ImportForm']))
        {
            $timeStart = getMicrotime();
            $model->attributes=$_POST['ImportForm'];
            if($model->validate())
            {
                if($model->csvFieldSeparator=='_TAB_')
                    $model->csvFieldSeparator = "\t";
                $model->csvFile=CUploadedFile::getInstance($model,'csvFile');
                $path = str_replace("\\",'/',Yii::app()->basePath.'/data/upload/'.$model->csvFile);
                $model->csvFile->saveAs($path);
                // Truncate Table?
                // DEBUG echo par($model->attributes);
                if($model->truncateTable==1) {
                    $model2 = new $destModelName;
                    // $command = Yii::app()->db->createCommand("DELETE FROM ".$model2->tableName());
                    $command = Yii::app()->db->createCommand("TRUNCATE TABLE ".$model2->tableName());
                    $rowsDeleted = $command->execute();
                }
                // Disable keys?
                if($model->disableyKeys) {
                    $sql = "ALTER TABLE ".$model2->tableName()." DISABLE KEYS";
                    $command = Yii::app()->db->createCommand($sql);
                    $resultDisableKeys = $command->execute();
                }
                // Lock table?
                if($model->lockTable) {
                    $sql = "LOCK TABLES ".$model2->tableName()." WRITE";
                    echo "<li>SQL: $sql";
                    $command = Yii::app()->db->createCommand($sql);
                    $resultLockTable = $command->execute();
                    echo par($resultLockTable);
                }

                // Current row index:
                $row = 0;
                $numAddedOK = 0; $numAddedNOK = 0;
                // Errors:
                $errors = array();
                // If we can open the uploaded file:
                if (($handle = fopen($path, "r")) !== FALSE) {
                    // DEBUG echo par($model->importSpec);
                    // {{{ Loop through each line
                    while (($data = fgetcsv($handle, 1000,  $model->csvFieldSeparator)) !== FALSE) 
                    {
                        // DEBUG echo "<li>row: $row";
                        // DEBUG echo par($data);
                        // Skip this first (n) line)
                        if($row+1<=$model->skipFirstNumLines) {
                            $row++;
                            // DEBUG echo "...skipped";
                            continue;
                        }
                        // Are we above max number of lines to read already?
                        if($row+1>$model->loadNbrOfLines and $model->loadNbrOfLines<>0)
                            break;
                        // Number of columns
                        $num = count($data);
                        // DEBUG echo "<p> $num fields in line $row: <br /></p>\n";
                        $row++;
                        // DEBUG
                        /*
                        for ($c=0; $c < $num; $c++) {
                            echo "<li>c: $c, value: " . $data[$c] . "<br />\n";
                        }
                         */
                        $model2 = new $destModelName;
                        $model2->prepareDateAttributesOnSave = $model->prepareDateAttributesOnSave;
                        foreach($model->importSpec['columns'] as $colIdx=>$attribute) {
                           // DEBUG echo "<li>column: ";
                           // DEBUG echo is_array($attribute) ? $attribute[0] : $attribute;
                           // DEBUG echo ", ";
                            if(isset($data[$colIdx])) {
                                $value = $data[$colIdx];
                                // DEBUG echo "value: $value";
                                if(is_array($attribute)) {
                                    $evalTerm = $attribute[1];
                                    $attribute = $attribute[0];
                                    eval("\$value = ".$evalTerm.";");
                                    // DEBUG echo " => $value";
                                }
                                $model2->$attribute = $value;
                            } else {
                                $errors[] = array($row,Yii::t('site',"Column {colIdx} doesn't exist in file",array('{colIdx}'=>$colIdx)));
                            }
                        }
                        // DEBUG echo par($model2->attributes);
                        $numAddedOK++;
                        try {
                            if(!$model2->save()) {
                                $errors[] = array($row,$model2->getErrors());
                                // echo par($errors[count($errors)-1]);
                                $numAddedOK--;
                                $numAddedNOK++;
                            }
                        } catch(Exception $e) {
                            // DEBUG echo par($e);
                            $errors[] = array($row,$e->getMessage());
                            $numAddedOK--;
                            $numAddedNOK++;
                            // {{{ Catch duplicate keys on FPR Items
                            if($_GET['spec']=='fprlateitems') {
                                $errorInfo = $e->errorInfo;
                                // DEBUG echo par($errorInfo);
                                if($errorInfo[1]==1062) {
                                    // Dupplicate Primary Key error
                                    $obj = new $destModelName;
                                    // Get previously saved item by displayIssueNbr
                                    $olderModel = $obj->findByPk($model2->displayIssueNbr);
                                    if(!is_null($olderModel)) {
                                        // DEBUG echo "<li>old item: ".$olderModel->displayIssueNbr.', associatedIssueNbr: '.$olderModel->associatedIssueNbr.'. ';
                                        // Add associatedIssueNbr to previous item
                                        $olderModel->associatedIssueNbr .= ';'.$model2->associatedIssueNbr;
                                        $result = $olderModel->save();
                                        // DEBUG echo $result ? 'Model saved. ' : 'Model NOT SAVED! ';
                                        // DEBUG echo "&rArr; ".$olderModel->associatedIssueNbr;
                                    }
                                }
                            }
                            // }}} 
                        }
                    } // }}} End lines loop
                    fclose($handle);
                }
                // Enable keys again?
                if($model->disableyKeys) {
                    $sql = "ALTER TABLE ".$model2->tableName()." ENABLE KEYS";
                    $command = Yii::app()->db->createCommand($sql);
                    $resultDisableKeys = $command->execute();
                }
                // Lock table?
                if($model->lockTable) {
                    $sql = "UNLOCK TABLES";
                    $command = Yii::app()->db->createCommand($sql);
                    $resultLockTable = $command->execute();
                    echo par($resultLockTable);
                }

                
                $msg = '<b>' . $importTitle . '</b><ul>';

                $msg .= '<li>' .Yii::t('site','Import File: {importFile}',array('{importFile}'=>basename($path))). '</li>';

                $timeEnd = getMicrotime();
                $timeDelta = $timeEnd - $timeStart;

                $msg .= 
                    '<li>'
                    . Yii::t(
                        'site',
                        '{rows} rows were read.<ul><li>{numAddedOK} items were inserted</li><li>{numAddedNOK} items were not inserted</li><li>Time used: {timeDelta} sec</li>',
                        array('{rows}'=>$row,'{numAddedOK}'=>$numAddedOK,'{numAddedNOK}'=>$numAddedNOK,'{timeDelta}'=>round($timeDelta,2))
                    )
                    . '</li>';
                // Show additional links
                if(is_array($model->importSpec['additionalLinks'])) {
                    foreach($model->importSpec['additionalLinks'] as $additionalLink)
                        $msg .= '<li>'.$additionalLink.'</li>';
                }
                // Re-do link
                $msg .= '</ul>';
                $msg .= '<p>'.CHtml::link(Yii::t('site','Re-do this import'),array('/admin/import/do','spec'=>$_GET['spec'])).'</p>';
                if(count($errors)>0) {
                    $msg .= "<b>".Yii::t('site','Errors')."</b><div style=\"width:250px;height:150px;overflow:auto\"><table style=\"font-size:0.8em;\">";
                    $msg .= '<thead><tr><th>'.Yii::t('site','Line').'</th><th>'.Yii::t('site','Error').'</th></tr></thead>';
                    $msg .= '<tbody>';
                    foreach($errors as $error) {
                        if(is_array($error[1])) {
                            ob_start();
                            echo par($error[1]);
                            $error[1] = ob_get_contents();
                            ob_end_clean();
                        }
                        $msg .= "<tr><td>{$error[0]}</td><td>{$error[1]}</td></tr>";
                    }
                    $msg .= '</tbody></table></div>';
                }
                Yii::app()->user->setFlash(
                    'success',
                    $msg
                );
                // redirect to success page
                $this->redirect(array($model->importSpec['redirect']));
            }
        } // }}} End form was submitted
        $this->render(
            'importForm', 
            array(
                'model'=>$model,
                'importTitle' => $importTitle
            )
        );
    } // }}} 
    // }}} End Actions
}

/* vim:set ai sw=4 sts=4 et fdm=marker fdc=4: */
